import re
import os

# <a href="" sort="0">代码</a>

with open('D:\BaiduNetdiskDownload\\爬虫从入门到应用\\2022_06_08直播数据解析_正则\\素材\\股票.html', 'r', encoding='utf-8') as f:
    gupiaoStr = f.read()

pipeiHead = re.compile('<a href="" sort="\d+">(.*?)</a>')
head_list = pipeiHead.findall(gupiaoStr)
pipeiJiancheng = re.compile('<td width="24%" class="align_center">(.*?)</td>', re.S)
pipei_jiancheng = pipeiJiancheng.findall(gupiaoStr)
# print(pipei_jiancheng[0].strip())   # strip()去掉空白字符（\r,\n,\t,' '）
head_list.insert(1, pipei_jiancheng[0].strip())

ff = open('gupiao_out.txt', 'a', encoding='utf-8')
ff.truncate(0)      # 清空文件

for item in head_list:
    ff.writelines(item + '\t\t\t\t\t')
ff.writelines('\n')

list_total = []
pipeiInf = re.compile('<tr>(.*?)</tr>')
info_list = pipeiInf.findall(gupiaoStr)
for item in range(3, len(info_list)):
    pipeiCode = re.compile('<a href="//stock.quote.stockstar.com/\d+.shtml">(\d+)</a>')
    code_list = pipeiCode.findall(info_list[item])

    pipeiName = re.compile('<a href="//stock.quote.stockstar.com/\d+.shtml">(\D+)</a>')
    name_list = pipeiName.findall(info_list[item])
    pipeiValue = re.compile('<td class="align_right ">([-+]?\d*\.\d+)</td>')
    ''' [-+]? 匹配一个可选的加号或减号，表示小数可以是正数或负数。
        \d* 匹配零个或多个数字，可以是整数部分。
        \. 匹配小数点。
        \d+ 匹配一个或多个数字，表示小数部分。
    '''
    value_list = pipeiValue.findall(info_list[item])
    for i in range(len(code_list)):
        value_list.insert(0, code_list[i])
        value_list.insert(1, name_list[i])
    list_total.append(value_list)

# list_total.sort(key=lambda x: x[2], reverse=False)
# print(list_total)
for k in range(len(info_list)-4):
    list_total[k][2] = float(list_total[k][2])
# 移除空列表
list_total = [row for row in list_total if row]
list_total.sort(key=lambda x: x[2], reverse=False)
# print(list_total)

for k in range(len(info_list)-4):
    for p in range(6):
        if p <= 1:
            ff.writelines(str(list_total[k][p]) + '\t\t\t\t')
        elif p == 2 or p == 4:
            ff.writelines(str(list_total[k][p]) + '\t\t\t\t\t\t')
        else:
            ff.writelines(str(list_total[k][p]) + '\t\t\t\t\t')
    ff.writelines('\n')
